import { useState, useEffect } from 'react'
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import Home from './pages/Home.jsx'
import Discover from './pages/Discover.jsx'
import Artist from './pages/Artist.jsx'
import ArtistDetail from './pages/ArtistDetail.jsx'
import Library from './pages/Library.jsx'
import PlaylistDetail from './pages/PlaylistDetail.jsx'
import AlbumDetail from './pages/AlbumDetail.jsx'
import Login from './pages/Login.jsx'
import Register from './pages/Register.jsx'
import Admin from './pages/Admin.jsx'
import NotFound from './pages/NotFound.jsx'
import VirtualListExample from './components/VirtualListExample.jsx'
import Header from './components/Header.jsx'
import Player from './components/Player.jsx'
import apiService from './utils/api.js'
import './App.css'

function App() {
  const [currentSong, setCurrentSong] = useState(null)
  const [isPlaying, setIsPlaying] = useState(false)
  const [playlist, setPlaylist] = useState([])
  const [currentIndex, setCurrentIndex] = useState(-1)

  // 模拟歌曲数据
  const featuredSongs = [
    {
      id: 1,
      title: '晴天',
      artist: '周杰伦',
      album: '叶惠美',
      cover: 'https://via.placeholder.com/300',
      audio: '' // 实际项目中这里会是真实的音频文件URL
    },
    {
      id: 2,
      title: '海阔天空',
      artist: 'Beyond',
      album: '乐与怒',
      cover: 'https://via.placeholder.com/300',
      audio: ''
    },
    {
      id: 3,
      title: '夜曲',
      artist: '周杰伦',
      album: '十一月的萧邦',
      cover: 'https://via.placeholder.com/300',
      audio: ''
    }
  ]
// 播放歌曲并增加播放量
  const playSong = (song) => {
    setCurrentSong(song)
    setIsPlaying(true)
    // 获取当前用户信息
    const user = apiService.getCurrentUser()
    console.log('当前用户:', user)
    // 只有当点击的歌曲与当前播放的歌曲不同时才增加播放量
    if (song && song.id && (!currentSong || currentSong.id !== song.id)) {
      const url = user && user.id ? `/my-music/songs/${song.id}/play` : `/songs/${song.id}/play`
      apiService.incrementPlayCount(url)
        .then(() => console.log('播放量增加成功'))
        .catch(err => console.error('播放量增加失败:', err))
    }
  }

  // 播放歌单
  const playPlaylist = async (playlistId) => {
    try {
      const response = await apiService.getPlaylistDetail(playlistId)
      if (response.code === 200 && response.data && response.data.songs && response.data.songs.length > 0) {
        setPlaylist(response.data.songs)
        setCurrentIndex(0)
        playSong(response.data.songs[0])
        alert(`已开始播放歌单，共${response.data.songs.length}首歌曲`)
      } else {
        alert('歌单为空或获取失败')
      }
    } catch (error) {
      console.error('播放歌单失败:', error)
      alert('播放歌单失败，请稍后再试')
    }
  }

  const togglePlay = () => {
    setIsPlaying(!isPlaying)
  }

  // 播放上一首歌曲
  const playPreviousSong = () => {
    if (playlist.length > 0) {
      const newIndex = currentIndex > 0 ? currentIndex - 1 : playlist.length - 1
      setCurrentIndex(newIndex)
      playSong(playlist[newIndex])
    }
  }

  // 播放下一首歌曲
  const playNextSong = () => {
    if (playlist.length > 0) {
      const newIndex = currentIndex < playlist.length - 1 ? currentIndex + 1 : 0
      setCurrentIndex(newIndex)
      playSong(playlist[newIndex])
    }
  }

  return (
    <BrowserRouter>
      <div className="app-container">
        {/* 顶部导航 - 使用新的Header组件 */}
        <Header />

        {/* 主要内容区域 */}
        <main className="app-main">
          <Routes>
            <Route path="/" element={<Home playSong={playSong} />} />
            <Route path="/discover" element={<Discover playSong={playSong} playPlaylist={playPlaylist} />} />
            <Route path="/artists" element={<Artist />} />
            <Route path="/artist/:id" element={<ArtistDetail playSong={playSong} />} />
            <Route path="/library" element={<Library playSong={playSong} playPlaylist={playPlaylist} />} />
            <Route path="/playlist/:id" element={<PlaylistDetail playSong={playSong} />} />
            <Route path="/album/:id" element={<AlbumDetail playSong={playSong} />} />
            <Route path="/login" element={<Login />} />
            <Route path="/register" element={<Register />} />
            <Route path="/admin" element={<Admin />} />
            <Route path="/virtual-list-example" element={<VirtualListExample />} />
            {/* 404 页面 - 通配符路由必须放在最后 */}
            <Route path="*" element={<NotFound />} />
          </Routes>
        </main>

        {/* 底部播放器 */}
        {currentSong && (
          <Player 
            song={currentSong} 
            isPlaying={isPlaying} 
            togglePlay={togglePlay} 
            playlist={playlist} 
            currentIndex={currentIndex} 
            playPreviousSong={playPreviousSong} 
            playNextSong={playNextSong} 
          />
        )}
      </div>
    </BrowserRouter>
  )
}

export default App